<template>
    <div style="width: 100%; padding: 0 10px; margin: 10px 0;">
        <div class="attendance-management" style="width: 100%; height: 80px;
            /* transform: translate(10px, 10px); */
            ">
            <div style="height: 100%; padding: 10px 0 10px 10px;
                width: 100%; line-height: 50px;">
                <b>
                    <span style="font-size: 28px; color: rgb(82, 89, 103);">
                        &nbsp;
                        <span style="font-size: 32px;">
                            考勤管理
                        </span>
                    </span>
                </b>
            </div>
        </div>
    </div>

    <div style="width: 100%; padding: 0 10px; margin: 10px 0;">
        <div class="attendance-management">
            <div class="container-header">
                <div class="header-title" title="我的考勤">我的考勤</div>
            </div>
            <div class="attendance-content">
                <!-- 筛选器区域 -->
                <div class="filter-section">
                    <div class="filter-item">
                        <div class="filter-head container-header">
                            <div class="head-label" title="归属考勤周期">归属考勤周期</div>
                        </div>
                        <div class="filter-content">
                            <el-select v-model="recordData.attendanceCycle" placeholder="" clearable filterable
                                @change="">
                                <el-option v-for="item in allCycles" :key="item" :label="item" :value="item">
                                </el-option>
                            </el-select>
                        </div>
                    </div>

                    <div class="filter-item">
                        <div class="filter-head container-header">
                            <div class="head-label" title="选择日期范围">选择日期</div>
                        </div>
                        <div class="filter-content">
                            <el-date-picker v-model="recordData.scope" style="width: " value-format="YYYY-MM-DD"
                                type="date" placeholder="" :size="size" />
                        </div>
                    </div>
                </div>

                <!-- 我的考勤列表 -->
                <div class="table-section">
                    <div class="filter-head container-header">
                        <div class="head-label" title="我的考勤">我的考勤</div>
                    </div>
                    <div class="filter-content">
                        <el-table :data="recordpage.records" show-overflow-tooltip stripe height="400px" @row-click="handleRowClick">
                            <el-table-column sortable v-for="col in myAttendance_columns" :prop="col.id" :key="col.id"
                                :label="col.label" :width="col.width">
                                <!-- 对上下班状态列单独处理，用 ElTag 渲染 -->
                                <template #default="scope">
                                    <template v-if="col.id === 'morningStatus' || col.id === 'afternoonStatus'">
                                        <el-tag effect="dark" :type="getTagType(scope.row[col.id])">
                                            {{ scope.row[col.id] }}
                                        </el-tag>
                                    </template>
                                    <template v-else>
                                        {{ scope.row[col.id] }}
                                    </template>
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>
                    <div style="margin: 15px;">
                        <el-pagination @current-change="loadAttendanceRecord" v-model:currentPage="recordpage.current"
                            :page-sizes="[2, 4, 6, 8, 10]" :page-size="recordpage.size" :total="recordpage.total"
                            background>
                        </el-pagination>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div style="width: 100%; padding: 0 10px; margin: 10px 0;">
        <div class="attendance-management">
            <div class="container-header">
                <div class="header-title" title="我的年假">我的年假</div>
            </div>
            <div class="attendance-content">
                <!-- 我的年假余额 -->
                <div class="table-section">
                    <div class="filter-head container-header">
                        <div class="head-label" title="我的年假余额">我的年假余额</div>
                    </div>
                    <div class="filter-content">
                        <el-table :data="annualpage.records" stripe height="330px" @row-click="handleRowClick1">
                            <el-table-column sortable v-for="col in myAnnualLeave_columns" :prop="col.id" :key="col.id"
                                :label="col.label" :width="col.width">
                            </el-table-column>
                        </el-table>
                    </div>
                    <div style="margin: 15px;">
                        <el-pagination @current-change="loadAnnualLeave" v-model:currentPage="annualpage.current"
                            :page-sizes="[2, 4, 6, 8, 10]" :page-size="annualpage.size" :total="annualpage.total"
                            background>
                        </el-pagination>
                    </div>
                </div>

                <!-- 所属年假周期 -->
                <div class="filter-item" style="width: 259px;">
                    <div class="filter-head container-header">
                        <div class="head-label" title="所属年周期">所属年周期</div>
                    </div>
                    <div class="filter-content">
                        <el-select v-model="recordData.annualLeave" placeholder="" clearable filterable
                            @change="loadLeaveAnnual">
                            <el-option v-for="item in allAnnual" :key="item" :label="item" :value="item">
                            </el-option>
                        </el-select>
                    </div>
                </div>

                <!-- 已请年假明细 -->
                <div class="table-section">
                    <div class="filter-head container-header">
                        <div class="head-label" title="已请年假明细">已请年假明细</div>
                    </div>
                    <div class="filter-content">
                        <el-table :data="leavePage.records" stripe height="330px" @row-click="handleRowClick2">
                            <template v-for="(item, index) in annualLeave_columns" :key="index">
                                <el-table-column sortable v-if="!item.children" :label="item.label" :prop="item.prop" />
                                <el-table-column v-else :label="item.label">
                                    <template v-for="(child, childIndex) in item.children" :key="childIndex">
                                        <el-table-column :label="child.label" :prop="child.prop" />
                                    </template>
                                </el-table-column>
                            </template>
                        </el-table>
                    </div>
                    <div style="margin: 15px;">
                        <el-pagination @current-change="loadLeaveAnnual" v-model:currentPage="leavePage.current"
                            :page-sizes="[2, 4, 6, 8, 10]" :page-size="leavePage.size" :total="leavePage.total"
                            background>
                        </el-pagination>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <el-dialog align-center destroy-on-close :title="title" v-model="dialogVisible" width="780px">
        <my-attendance :attendanceData="selectedRow"></my-attendance>
    </el-dialog>

    <el-dialog align-center destroy-on-close :title="title" v-model="dialogVisible1" width="780px">
        <my-annual-leave :annualLeaveData="selectedRow1"></my-annual-leave>
    </el-dialog>

    <el-dialog align-center destroy-on-close :title="title" v-model="dialogVisible2" width="780px">
        <annual-leave :annualLeave="selectedRow2"></annual-leave>
    </el-dialog>

</template>

<script setup>
import { ref, watch } from 'vue'
import myAttendance from './myAttendance.vue'
import myAnnualLeave from './myAnnualLeave.vue'
import annualLeave from './annualLeave.vue'
import request from '@/api/request';

const title = ref('')

const allCycles = ref([])
const allAnnual = ref([])

const recordData = ref({})

// 数据
let recordpage = ref({
    current: 1,
    size: 7,
    total: 0,
    records: []
})

let annualpage = ref({
    current: 1,
    size: 4,
    total: 0,
    records: []
})

let leavePage = ref({
    current: 1,
    size: 4,
    total: 0,
    records: []
})

let loadAllCycles = () => {
    request({
        url: "/attendanceRecord/statisticsAttendanceCycle",
        method: "get"
    }).then(resp => {
        allCycles.value = resp.data
        console.log(allCycles)
    })
}

let loadAllAnnual = () => {
    request({
        url: "/leaveApplication/findAllAnnual",
        method: "get",
        params: {
            leaveType: '年假'
        }
    }).then(resp => {
        allAnnual.value = resp.data
        console.log(allAnnual)
    })
}

// 获取session中的用户信息 - 需要解析JSON字符串
let user = JSON.parse(sessionStorage.getItem('user') || '{}');
console.log(user);

let loadAttendanceRecord = () => {
    let startDate = null;
    // let endDate = null;

    if (recordData.value.scope) {
        startDate = recordData.value.scope;
        // endDate = recordData.value.scope[1];
    }

    request({
        url: "/attendanceRecord/page",
        method: "get",
        params: {
            current: recordpage.value.current,
            size: recordpage.value.size,
            userId: user.employeeId,
            attendanceCycle: recordData.value.attendanceCycle,
            startDate: startDate,
            // endDate: endDate
        }
    }).then(resp => {
        if (resp.data.records) {
            resp.data.records = resp.data.records.map(record => {
                return {
                    ...record,
                    username: user.employeeName || user.employeeName,
                    department: user.department.deptName || user.department.deptName,
                }
            });
        }
        recordpage.value = resp.data
        console.log(resp.data)
    })
}

let loadAnnualLeave = () => {
    request({
        url: "/annualLeave/page",
        method: "get",
        params: {
            current: annualpage.value.current,
            size: annualpage.value.size,
            userId: user.employeeId,
        }
    }).then(resp => {
        annualpage.value = resp.data
        console.log(resp.data)
    })
}

let loadLeaveAnnual = () => {
    request({
        url: "/leaveApplication/page",
        method: "get",
        params: {
            current: leavePage.value.current,
            size: leavePage.value.size,
            userId: user.employeeId,
            leaveType: '年假',
            attendanceCycle: recordData.value.annualLeave
        }
    }).then(resp => {
        leavePage.value = resp.data
        console.log(resp.data)
    })
}

loadAllCycles()
loadAllAnnual()
loadAttendanceRecord()
loadAnnualLeave()
loadLeaveAnnual()

watch([() => recordData.value.attendanceCycle, () => recordData.value.scope], (newCycle, newScope) => {
    if (newCycle || newScope) {
        loadAttendanceRecord()
    }
})

const dialogVisible = ref(false)
const selectedRow = ref({})
const dialogVisible1 = ref(false)
const selectedRow1 = ref({})
const dialogVisible2 = ref(false)
const selectedRow2 = ref({})

const handleRowClick = (row, event, column) => {
    console.log(row);
    selectedRow.value = row
    title.value = selectedRow.value.recordDate;
    dialogVisible.value = true
}

const handleRowClick1 = (row, event, column) => {
    console.log(row);
    selectedRow1.value = row
    title.value = selectedRow1.value.annualCycle;
    dialogVisible1.value = true
}

const handleRowClick2 = (row, event, column) => {
    console.log(row);
    selectedRow2.value = row
    title.value = selectedRow2.value.leaveDate;
    dialogVisible2.value = true
}

// 记录原始 body 样式
let originalBodyStyle = '';

// 对话框打开处理
const handleOpen = () => {
    // 保存原始 body 样式
    originalBodyStyle = document.body.style.cssText;
    // 禁止背景滚动
    document.body.style.cssText += ';overflow: hidden; position: fixed; width: 100%';
};

// 对话框关闭处理
const handleClose = () => {
    // 恢复 body 样式
    document.body.style.cssText = originalBodyStyle;
};

// 对话框完全关闭后重置状态
const handleClosed = () => {
    // 确保状态重置
    document.body.style.overflow = '';
    document.body.style.position = '';
    document.body.style.width = '';
};

let myAttendance_columns = [
    { id: "recordDate", label: "日期" },
    { id: "username", label: "姓名" },
    { id: "department", label: "所在部门" },
    { id: "attendanceCycle", label: "归属考勤周期" },
    { id: "morningStatus", label: "上午签到状态" },
    { id: "afternoonStatus", label: "下午签退状态" },
    { id: "location", label: "定位" },
    { id: "lateMinutes", label: "迟到分钟数" },
    { id: "earlyLeaveMinutes", label: "早退分钟数" }
]

let myAnnualLeave_columns = [
    { id: "annualCycle", label: "年周期" },
    { id: "annualDate", label: "年假天数(天)" },
    { id: "useDate", label: "已请年假天数(天)" },
    { id: "surplusDate", label: "剩余年假天数" },
]



const annualLeave_columns = ref([
    // {
    //     label: '姓名',
    //     prop: 'name',
    // },
    // {
    //     label: '所在部门',
    //     prop: 'department',
    // },
    {
        label: '年周期',
        prop: 'annualLeave.annualCycle',
    },
    {
        label: '年假天数（天）',
        prop: 'annualLeave.annualDate',
    },
    {
        label: '合计请假天数',
        prop: 'duration',
    },
    {
        label: '请假后剩余年假天数',
        prop: 'annualLeave.surplusDate',
    },
    {
        label: '请假事由说明',
        prop: 'reason',
    },
    {
        label: '请假日期',
        children: [
            {
                label: '请假日期',
                prop: 'leaveDate',
            },
            {
                label: '请假时段',
                prop: 'leavePeriod',
            },
            {
                label: '请假天数小计',
                prop: 'duration',
            },
            {
                label: '归属考勤周期',
                prop: 'attendanceCycle',
            },
        ],
    },
]);

// 根据状态返回 Tag 类型，可自定义拓展
const getTagType = (status) => {
    switch (status) {
        case "正常":
        case "外勤":
            return "success";
        case "迟到":
        case "缺勤":
        case "早退":
        case "未签到":
            return "danger";
        case "调休":
        case "加班":
        case "请假":
        case "出差":
            return "primary";
        default:
            return "default";
    }
};

</script>

<style scoped>
.attendance-management {
    background: #fff;
    -webkit-box-shadow: 0 2px 6px 0 rgba(84, 48, 132, .1);
    box-shadow: 0 2px 6px 0 rgba(84, 48, 132, .1);
    width: 100%;
    margin-bottom: 20px;
}

.container-header {
    padding: 5px;
    line-height: 30px;
    height: 40px;
}

.header-title {
    font-weight: 700;
    padding: 0 5px;
}

.head-label {
    line-height: 20px;
}

.attendance-content {
    padding: 15px;
}

.filter-section {
    display: flex;
    gap: 20px;
    margin-bottom: 20px;
    flex-wrap: wrap;
}

.filter-item {
    min-width: 250px;
}

.filter-item .filter-head {
    margin-bottom: 5px;
}

.table-section {
    margin-bottom: 20px;
}

.table-section .filter-head {
    margin-bottom: 10px;
}
</style>